package com.andy.image

import android.content.Context
import android.graphics.drawable.Drawable
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition

object ImageManager {

    /**
     * 显示圆形图片
     *
     * @param ctx Context
     * @param imageUrl String
     * @param view ImageView
     * @param placeholder Int?
     */
    fun showCircleImage(ctx: Context, imageUrl: String?, view: ImageView, placeholder: Int? = null) {
        var req = Glide.with(ctx).load(imageUrl)
        if (placeholder != null && placeholder > 0)
            req = req.placeholder(placeholder).error(placeholder)

        req.transform(CircleCrop()).into(view)
    }

    fun showImage(ctx: Context, imageUrl: String?, view: ImageView, placeholder: Int? = null) {
        var req = Glide.with(ctx).load(imageUrl)
        if (placeholder != null && placeholder > 0)
            req = req.placeholder(placeholder).error(placeholder)

        req.into(view)
    }

    /**
     * 显示radius图片
     */
    fun showCornerImage(ctx: Context, imageUrl: String?, view: ImageView, radius: Int = 0, placeholder: Int? = null) {
        var req = Glide.with(ctx).load(imageUrl)
        if (placeholder != null && placeholder > 0)
            req = req.placeholder(placeholder).error(placeholder)

        req.transform(RoundedCorners(radius)).into(view)
    }

    fun showAvatar(ctx: Context, imageUrl: String?, view: ImageView) {
        showCircleImage(ctx, imageUrl, view, R.drawable.ic_avatar_default)
    }

    /**
     * 设置背景
     */
    fun setDrawable(ctx: Context, imageUrl: String?, placeholder: Int? = null, callBack: ((drawable: Drawable?) -> Unit)? = null) {
        var req = Glide.with(ctx).load(imageUrl)
        if (placeholder != null && placeholder > 0)
            req = req.placeholder(placeholder).error(placeholder)

        req.centerCrop().into(object : CustomTarget<Drawable>() {
            override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) {
                callBack?.invoke(resource)
            }

            override fun onLoadFailed(errorDrawable: Drawable?) {
                callBack?.invoke(null)
            }

            override fun onLoadCleared(placeholder: Drawable?) {}
        })
    }
}